package adm.hikingapp;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import Dominio.Ruta;
import adm.controlador.Controller;
import android.os.AsyncTask;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RatingBar;
import android.widget.TextView;

public class ComentarRuta extends ClaseBase {
	RatingBar Puntuacion;
	Ruta ruta = null;
	EditText Comentario = null;
	private TextView 	   nombrePantalla;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_comentar_ruta);
	    nombrePantalla = (TextView) findViewById(R.id.nombrePantalla);
			nombrePantalla.setText(R.string.comentrut);
		 Bundle bundle = getIntent().getExtras();
			if(bundle != null){
				ruta = (Ruta) bundle.getSerializable("Ruta");
			}
	                
		
		ImageButton btn_home = (ImageButton)findViewById(R.id.btnHome);
			btn_home.setOnClickListener(new OnClickListener(){
				public void onClick(View v){
					Intent intent = new Intent(ComentarRuta.this, Dashboard.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					finish();				
				}
			});	
		Button Aceptar = (Button)findViewById(R.id.botonAceptarComentario);
		Comentario = (EditText)findViewById(R.id.ComentarText);
		Puntuacion = (RatingBar)findViewById(R.id.ratingBar1);
			Aceptar.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					// TODO Auto-generated method stub
					new comentarios(ComentarRuta.this).execute();
					Intent intent = new Intent(ComentarRuta.this, Dashboard.class);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					finish();			
					
				}
			});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_comentar_ruta, menu);
		return true;
	}
	
	static class comentarios extends AsyncTask<Void, Void, Void>{
		WeakReference<ComentarRuta> context;
		public comentarios(ComentarRuta activity){
			context = new WeakReference<ComentarRuta>(activity);
		}
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			
		}

		@SuppressLint("NewApi")
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			ComentarRuta activity = context.get();
			
			
			String consultacoments = "SELECT COUNT(*) AS numero FROM Puntuaciones where Ruta_id='"+activity.ruta.getId()+"'";
			SharedPreferences preferencias = activity.getSharedPreferences("preferencias", Context.MODE_PRIVATE);
			String insertaComent = "INSERT INTO Comentario  (Ruta_id, User, Texto) " +
					"VALUES ("+activity.ruta.getId()+", '"+
					preferencias.getString("nick", "Anonimo")+"', '"+
					activity.Comentario.getText().toString()+"');";
			
			
			JSONArray aux2 = Controller.ConsultaBD(consultacoments);
			JSONObject media = null;
			JSONObject numero = null;
			
			try {
				media = aux2.getJSONObject(0);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			Integer suma = null;
			
			try {
				suma = Integer.valueOf(media.get("numero").toString());
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			Float resultado = (float) (((activity.ruta.getPuntuacion()*suma)+(activity.Puntuacion.getRating()*2))/(suma+1));
			String actualizaruta = "UPDATE Ruta SET Puntuacion = '"+
									resultado+"' WHERE Ruta_id = '"+activity.ruta.getId()+"';";
			String insertaPuntuacion = "INSERT INTO Puntuaciones (Ruta_id, Puntuacion, User) VALUES ("+activity.ruta.getId()+
					", "+activity.Puntuacion.getRating()*2+", '"+preferencias.getString("nick", "Anonimo")+"');";
			if(activity.Comentario.getText().toString().length()>2)
			Controller.InsertaBD(insertaComent);
			if(activity.Puntuacion.getRating()>0){
			Controller.InsertaBD(insertaPuntuacion);
			Controller.UpdateBD(actualizaruta);	
			}
			
			return null;
		}
		
		
	}

}
